#include "restore.h"
#include <filesystem>
#include <fstream>
#include <iostream>
#include <sstream>

namespace fs = std::filesystem;

void RestoreBackup(const std::string &backupDir, const std::string &restoreDir) {
    try {
        fs::path backupPath(backupDir);
        fs::path restorePath(restoreDir);

        // Create restore directory if it does not exist
        fs::create_directories(restorePath);

        // Read metadata
        std::ifstream metaFile(backupPath / "metadata.txt");
        std::string line;
        while (std::getline(metaFile, line)) {
            std::string action, path;
            std::istringstream iss(line);
            iss>>action;
            iss>>path;
            if (iss >>  path) {
                // std::cout<<action<<"c\n";
                fs::path fullPath = backupPath / path;
                if (action == "modified"||action=="added") {
                    fs::copy(fullPath, restorePath / path, fs::copy_options::overwrite_existing | fs::copy_options::recursive);
                }else if(action=="deleted"){
                    fs::remove(restorePath / path);
                }
            }
        }
        metaFile.close();

        std::cout << "Restore completed successfully.\n";
    } catch (const fs::filesystem_error &err) {
        std::cerr << "Filesystem error: " << err.what() << '\n';
    }
}
